var os = require("os");
var exec = require("child_process").exec;

//过虑掉字符串首尾格式，替换字符串中的多个空格为一个空格
function trim(s) {
  return s.replace(/(^\s*)|(\s*$)/g, "").replace(/\s+/g, " ");
}

function getSystemInfo(ctx) {
  //df --total |grep total
  var sysinfo = {
    hostname: os.hostname(),
    systemtype: os.type(),
    release: os.release(),
    uptime: os.uptime(),
    loadavg: os.loadavg(),
    totalmem: os.totalmem(),
    freemem: os.freemem(),
    cpus: os.cpus(),
    disk: "",
    else: "hello",
  };

  return new Promise((resolve, reject) => {
    exec("df -h", function (error, stdout, stderr) {
      if (error !== null) {
        console.log("exec error: " + error);
        reject(error);
      } else {
        var tmp = trim(stdout).split(" ");
        sysinfo.disk = { total: tmp[1], used: tmp[2], free: tmp[3] };
        resolve(sysinfo);
      }
    });
  });
}

module.exports = getSystemInfo;

// async function test(){
//   console.log(JSON.stringify(await getSystemInfo(), '\t', 4));
// }
// test()